class_name UnitStateHit
extends StateBase

var unit: UnitBase
@onready var recover_approach_timer: Timer = $RecoverApproachTimer


func on_enter(owner = null, params = null):
	if recover_approach_timer:
		recover_approach_timer.stop()
	
	unit = owner as UnitBase
	
	var knock_back_velocity = unit.current_hit_data.knockback - unit.unit_data.get_anti_knockback()
	if knock_back_velocity <= 0:
		knock_back_velocity = 0
	
	unit.velocity.x = unit.get_face() * -1 * knock_back_velocity
	unit.velocity.y = unit.current_hit_data.affect_vertical_velocity
	unit.level.emit_particle("particle_hit_blood", unit.get_random_hurt_position())
	unit.level.emit_particle("particle_hit_effect", unit.get_random_hurt_position())
	
	if unit.current_hit_data.is_critical:
		unit.level.emit_particle("particle_critical_attack_effect", unit.get_random_hurt_position())
		if unit.light_animation_player:
			unit.light_animation_player.play("CriticalLightFlash")
		
	var damage_scale = 1.5 if unit.current_hit_data.is_critical else 1.0
	var damage = unit.current_hit_data.actual_damage
	unit.level.raise_damage_number(damage, unit.get_random_hurt_position() + Vector2.UP * 16, damage_scale)
	
	await get_tree().create_timer(0.1).timeout
	if unit.is_dead:
		unit.states.transition("Death")
	else:
		if recover_approach_timer:
			recover_approach_timer.stop()
			recover_approach_timer.start()
			unit.velocity = Vector2.ZERO
		else:
			unit.states.transition("Approach")
	

func on_exit(owner = null):
	unit.velocity = Vector2.ZERO


func on_process(delta: float, owner = null):
	pass
	
	
func on_physics_process(delta: float, owner = null):
	unit.move_and_slide()
	
	
	
